package com.hc.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Date;

public class FileTool {
	/**
	 * 检查文件是否指定的文件
	 * 
	 * @param fileName
	 * @param fileType
	 * @return
	 */
	public static boolean checkFileType(String fileName, String fileType) {
		boolean flag = false;
		if (fileName != null && fileName.length() > 0) {
			int n = fileName.lastIndexOf(".");
			String type = fileName.substring(n + 1, fileName.length());
			if (null != type && type.toLowerCase().equals(fileType)) {
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * 删除文件
	 * 
	 * @param filePath
	 */
	public static void deleteFile(String filePath) {
		File file = new File(filePath);
		file.delete();
	}

	/**
	 * 计算拷贝时间
	 * 
	 * @param file1Path
	 * @param file2Path
	 * @return
	 * @throws Exception
	 */
	public static long forChannel(String file1Path, String file2Path)
			throws Exception {
		File f1 = new File(file1Path);
		File f2 = new File(file2Path);
		if (!f2.exists()) {
			f2.createNewFile();
		}

		long time = new Date().getTime();
		int length = 2097152;
		FileInputStream in = new FileInputStream(f1);
		FileOutputStream out = new FileOutputStream(f2);
		FileChannel inC = in.getChannel();
		FileChannel outC = out.getChannel();
		ByteBuffer b = null;
		while (true) {
			if (inC.position() == inC.size()) {
				inC.close();
				outC.close();
				return new Date().getTime() - time;
			}
			if ((inC.size() - inC.position()) < length) {
				length = (int) (inC.size() - inC.position());
			} else {
				length = 2097152;
			}
			b = ByteBuffer.allocateDirect(length);
			inC.read(b);
			b.flip();
			outC.write(b);
			outC.force(false);
		}
	}
}
